const Room = require('./Room')

class Rooms {
    constructor(dao) {
        this.dao = dao
        this._rooms = null
    }

    async getRoom(name) {
        let rooms = await this.list()
        if (rooms.includes(name)) {
            return this._rooms[name]
        } else {
            throw Error(`房间 ${name} 不存在`)
        }
    }

    async list() {
        if (!this._rooms) {
            this._rooms = {}
            let dr = await this.dao.rooms()
            for (let i of dr) {
                this._rooms[i.name] = new Room(i.public)
            }
        }
        return Object.keys(this._rooms)
    }

    async newRoom(room, user, pub) {
        if (!(await this.list()).includes(room)) {
            await this.dao.newRoom(room, user.name, pub)
            this._rooms[room] = new Room(pub)
        } else {
            throw new Error(`房间 ${room} 已存在`)
        }
        return this
    }

    async delRoom(room) {
        if ((await this.list()).includes(room)) {
            await this.dao.delRoom(room)
            delete this._rooms[room]
        }
        return this
    }

    async joinRoom(room, user) {
        try {
            await this.dao.joinRoom(room, user.name)
            return (await this.getRoom(room)).join(user)
        } catch({message}) {
            throw new Error(message)
        }
    }

    async leaveRoom(room, user) {
        await this.dao.leaveRoom(room, user.name)
        (await this.getRoom(room)).leave(user)
    }

    removeUser(user) {
        for (let i in this._rooms) {
            this._rooms[i].leave(user)
        }
    }
}

module.exports = Rooms